import { NextRequest, NextResponse } from 'next/server'
import { getReviews } from '@/lib/database'
import { withErrorHandling } from '@/lib/auth-middleware'

export const GET = withErrorHandling(async (request: NextRequest, context: any) => {
  // 从URL中提取工具ID
  const url = new URL(request.url)
  const pathSegments = url.pathname.split('/')
  const toolId = pathSegments[pathSegments.length - 3] // stats前面的ID

  if (!toolId) {
    return NextResponse.json(
      { error: '工具ID不能为空' },
      { status: 400 }
    )
  }

  try {
    const reviews = await getReviews()
    const toolReviews = reviews.filter(review => review.toolId === toolId)

    if (toolReviews.length === 0) {
      return NextResponse.json({
        success: true,
        data: {
          totalReviews: 0,
          averageRating: 0,
          ratingDistribution: {
            1: 0,
            2: 0,
            3: 0,
            4: 0,
            5: 0
          }
        }
      })
    }

    // 计算评分分布
    const ratingDistribution = {
      1: 0,
      2: 0,
      3: 0,
      4: 0,
      5: 0
    }

    toolReviews.forEach(review => {
      const rating = review.rating as keyof typeof ratingDistribution
      if (rating >= 1 && rating <= 5) {
        ratingDistribution[rating]++
      }
    })

    // 计算平均评分
    const totalRating = toolReviews.reduce((sum, review) => sum + review.rating, 0)
    const averageRating = totalRating / toolReviews.length

    return NextResponse.json({
      success: true,
      data: {
        totalReviews: toolReviews.length,
        averageRating: Math.round(averageRating * 10) / 10, // 保留一位小数
        ratingDistribution
      }
    })
  } catch (error) {
    console.error('获取评价统计失败:', error)
    return NextResponse.json(
      { error: '服务器内部错误' },
      { status: 500 }
    )
  }
})
